#!/bin/bash

VAR_DIR=/tmp
STATE_FILE=${VAR_DIR}/proc_stat

read -a cpu_last_state < /proc/stat

if [ ! -f $STATE_FILE ] ; then 
    echo "Warning: There is no prev state file!"
    echo ${cpu_last_state[*]} > $STATE_FILE && echo "...was"
    exit 1
fi

read -a cpu_prev_state < $STATE_FILE
echo ${cpu_last_state[*]} > $STATE_FILE

for i in {0..9} ; do
    cpu_vol[$i]=$((cpu_last_state[$i]-cpu_prev_state[$i]))
    SUM=$((SUM+cpu_vol[$i]))
done

for MODE in USER NICE SYSTEM IDLE IOWAIT IRQ SOFTIRQ STEAL GUEST ; do
    ((++n))
    FL=$((cpu_vol[$n]*10000/SUM))
    FL_X000=${FL: -4:1} #; FL_X000=${FL_X000:-0}
    FL_0X00=${FL: -3:1} ; FL_0X00=${FL_0X00:-0}
    FL_00X0=${FL: -2:1} ; FL_00X0=${FL_00X0:-0}
    FL_000X=${FL: -1:1} ; FL_000X=${FL_000X:-0}
    eval ${MODE}=${FL_X000}${FL_0X00}.${FL_00X0}${FL_000X}
done

echo $USER $NICE $SYSTEM $IDLE $IOWAIT $IRQ $SOFTIRQ $STEAL $GUEST
